#include "flowproc.h"
#include "lgCommon.h"
#include "lgQuantRec.h"


volatile uint8_t   gRunState;         //运行状态
volatile uint8_t   gSwitchBigState;   //大阀状态
volatile uint8_t   gSwitchTinyState;  //小阀状态

int       gNoFlowConSec = 0;  //无流量连续秒

#define  NO_FLOW   (Xsram[INLET_FREQ].fValue < 2.0f)

uint32_t  gStartFlowInt;   //开始流量整数 
float     gStartFlowDec;   //开始流量小数


uint32_t    gStartTime = 0;    //本次开始时间
int       gZeroDelayCnt = 0;




RelayOper   gIdleRelay;
RelayOper   gRunRelay;

void  FlowInit()
{
    gRunState = STATE_IDLE;
    
    gNoFlowConSec = 0;
    if(sys_cfg_tab[START_RELAY_STATE] != 0)
    {
        gIdleRelay = RELAY_OFF;
        gRunRelay = RELAY_ON;
    }
    else
    {
        gIdleRelay = RELAY_OFF;
        gRunRelay = RELAY_ON;
    }
//1. 阀门关闭
    lgSitchCtrl(SWITCH_BIG,gIdleRelay);
    lgSitchCtrl(SWITCH_TINY,gIdleRelay);
//2. 初始化当前的累积量设定
    gStartTime = 0;
    gStartFlowInt = 0;
    gStartFlowDec = 0;
    Xsram[FeedDuration].lValue = 0;
}

void  KeyStartProc()
{
    if(gRunState ==  STATE_IDLE || gRunState == STATE_PAUSE)
    {
	//1. 阀门打开
      
        gNoFlowConSec = 0;
        if(sys_cfg_tab[QUANTIFY_MODE] == 0)
        {
             if(STATE_PAUSE != gRunState)
	    {//不是暂停开始，新的定量过程

               lgSitchCtrl(SWITCH_BIG,gRunRelay);
               gRunState = STATE_PUMP_RELAY;
               gZeroDelayCnt = user_cfg_tab[PUMP_RELAY_DELAY] * 5;
            }
            else
            {
                 lgSitchCtrl(SWITCH_BIG,gRunRelay);
                 lgSitchCtrl(SWITCH_TINY,gRunRelay); 
                  //必须放最后，前边判断是否暂停需要注意，改了就不是暂停了，bug'
                 gRunState = STATE_RUN;
            } 
        }
        else
        {
            lgSitchCtrl(SWITCH_BIG,gRunRelay);
            lgSitchCtrl(SWITCH_TINY,gRunRelay); 

              
            if(STATE_PAUSE != gRunState)
	    {//不是暂停开始，新的定量过程

                gStartTime  =  getTimeSecNow();
                gStartFlowInt = Xsram[Fsum].lValue;
                gStartFlowDec = Xsram[SumInFlowVAL].fValue;
                Xsram[FeedVal].fValue = 0;
            }
          
            //必须放最后，前边判断是否暂停需要注意，改了就不是暂停了，bug'
            gRunState = STATE_RUN;
        }

	
        SEGGER_RTT_printf(0, "start time %02d-%02d-%02d %02d:%02d:%02d\r\n", 
                   timeNow.nYear, timeNow.nMonth,  timeNow.nDay,
                   timeNow.nHour, timeNow.nMinute, timeNow.nSecond);


	  

    }
      
}


void  KeyPauseProc()
{
    if(gRunState == STATE_RUN || STATE_ZERO_DELAY == gRunState)
    {
     	//状态更改位暂停
        gRunState = STATE_PAUSE;
        gZeroDelayCnt = 0;
	   //断开阀门
//1. 阀门关闭
       lgSitchCtrl(SWITCH_BIG,gIdleRelay);
       lgSitchCtrl(SWITCH_TINY,gIdleRelay);
         
       gNoFlowConSec = 0;

       SEGGER_RTT_printf(0, "pause time %02d-%02d-%02d %02d:%02d:%02d\r\n", 
                   timeNow.nYear, timeNow.nMonth,  timeNow.nDay,
                   timeNow.nHour, timeNow.nMinute, timeNow.nSecond);

    }
	
}




void  KeyStopProc(QuantiEndFlag  endReason)
{
	//累积清零，
	//打开阀门一次
    stQuantOperRec   newRec;
    uint32_t timeNowX =  getTimeSecNow();

    if((STATE_PAUSE == gRunState ) || (endReason == End_NoFlow))
    {
    	gRunState = STATE_IDLE;
         gZeroDelayCnt = 0;

        SEGGER_RTT_printf(0, "stop time %02d-%02d-%02d %02d:%02d:%02d\r\n", 
                   timeNow.nYear, timeNow.nMonth,  timeNow.nDay,
                   timeNow.nHour, timeNow.nMinute, timeNow.nSecond);
	
       newRec.startTime    = gStartTime;
       newRec.stopTime     = timeNowX;
       newRec.fQuantiSche  = user_cfg_tab[QUANTIFY_CUR_VAL];
       newRec.fLastVal     = Xsram[FeedVal].fValue;
       newRec.nEndFlag     = endReason;
       
       lgSitchCtrl(SWITCH_BIG,gIdleRelay);
       lgSitchCtrl(SWITCH_TINY,gIdleRelay);
       
       lgAddQuantOpernRec(&newRec);
         
  
       gNoFlowConSec = 0;

       Xsram[FeedVal].fValue      = 0;
       Xsram[FeedSum].fValue      +=   Xsram[FeedVal].fValue;
       Xsram[FeedTimes].lValue    += 1;
       Xsram[FeedDuration].lValue += (newRec.stopTime - gStartTime);
    }
	//状态位 计量中
}

void KeyClearReset()
{
   if(STATE_IDLE == gRunState ||  STATE_ZERO_DELAY == gRunState)
   {
       Xsram[FeedVal].fValue      = 0;
       Xsram[FeedTimes].lValue    = 0; 
       Xsram[FeedDuration].lValue = 0;
       Xsram[FeedSum].fValue      = 0;
   }
} 



void  lgOnTimeFlowCheck()
{
    stQuantOperRec   newRec;
     
    
    //状态位计量中
    //   计算流量
    //  当定制流量到达定量设定
	//      状态更改位暂停，
	//      断开阀门	
    //其他状态
    // 忽略
    if(gRunState == STATE_IDLE || gRunState == STATE_PAUSE)
        return;
          
    if(sys_cfg_tab[QUANTIFY_MODE] == 0 && STATE_PUMP_RELAY == gRunState )
    {//一级控制
      
        if(gZeroDelayCnt >0)
        {
           gZeroDelayCnt--;
             
           return ;
        }
       
         if(gZeroDelayCnt <= 0)
         {
               

               lgSitchCtrl(SWITCH_TINY,gRunRelay); 
                          
               if(STATE_PAUSE != gRunState)
	       {//不是暂停开始，新的定量过程
                   gStartTime  =  getTimeSecNow();
                   gStartFlowInt = Xsram[Fsum].lValue;
                   gStartFlowDec = Xsram[SumInFlowVAL].fValue;
                   Xsram[FeedVal].fValue = 0;
               }
               //一定要在 if(STATE_PAUSE != gRunState) 后边，不然bug
               gRunState = STATE_RUN;
         }
    }
        
    uint32_t timeNowX =  getTimeSecNow();
        
    float  fFlow = Xsram[Fsum].lValue - gStartFlowInt +
                 ( Xsram[SumInFlowVAL].fValue -gStartFlowDec);

    if(gRunState == STATE_RUN)
    {
        Xsram[FeedVal].fValue = fFlow;
          
        if(Xsram[INLET_FREQ].fValue < 2.0f)
        {//如果正加料中间无脉冲，则无Flow 个数加1  
           gNoFlowConSec += 1;
        }

//供料中但是持续 sys_cfg_tab[START_NOFLOW_STOP] 秒无流量，关闭定量控制，
//这个检测周期200ms一次，所以一秒五次，乘以5
        if(gNoFlowConSec > sys_cfg_tab[START_NOFLOW_STOP]*5)
        { 
            KeyStopProc(End_NoFlow);
            return;
        }
    }
    else
    {
         gNoFlowConSec = 0;
         Xsram[FeedVal].fValue  = user_cfg_tab[QUANTIFY_CUR_VAL];
    }
    
      
    if(sys_cfg_tab[QUANTIFY_MODE] == 0)
    {//一级控制，直接就回零
           
          if( (fFlow >  (user_cfg_tab[QUANTIFY_CUR_VAL] - user_cfg_tab[QUAN_PRE_SMALL_VAL]))
           && gRunState == STATE_RUN )
         {
             gRunState =  STATE_ZERO_DELAY;
             

            if(sys_cfg_tab[AUTO_FEED_EN] != 0)
            {
                gZeroDelayCnt = user_cfg_tab[ZERO_DELAY] * 5; //200ms调用一次，所以，这个回零延时 乘以5 ，代表有多少个 200ms
            }
            else
            {
                gZeroDelayCnt = 5; 
            }
             
             lgSitchCtrl(SWITCH_BIG,gIdleRelay);
             lgSitchCtrl(SWITCH_TINY,gIdleRelay);
                               
             Xsram[FeedVal].fValue = user_cfg_tab[QUANTIFY_CUR_VAL];
             return;
         }
     }
     else
     {
 
                                    // 1  - 0.5  = 9.5           1-0.02 = 9.98
        if( (fFlow >  (user_cfg_tab[QUANTIFY_CUR_VAL] - user_cfg_tab[QUAN_PRE_BIG_VAL])) &&
             (fFlow <  (user_cfg_tab[QUANTIFY_CUR_VAL] - user_cfg_tab[QUAN_PRE_SMALL_VAL])) &&
             gRunState == STATE_RUN)
        {//大阀需要关闭
            lgSitchCtrl(SWITCH_BIG,gIdleRelay);
            return;
         }
         else if( (fFlow >  (user_cfg_tab[QUANTIFY_CUR_VAL] - user_cfg_tab[QUAN_PRE_SMALL_VAL])) &&
           gRunState == STATE_RUN )
         {//小阀需要关闭
            lgSitchCtrl(SWITCH_TINY,gIdleRelay);
            gRunState =  STATE_ZERO_DELAY;
            Xsram[FeedVal].fValue = user_cfg_tab[QUANTIFY_CUR_VAL];
            
            if(sys_cfg_tab[AUTO_FEED_EN] != 0)
            {
                gZeroDelayCnt = user_cfg_tab[ZERO_DELAY] * 5; //200ms调用一次，所以，这个回零延时 乘以5 ，代表有多少个 200ms
            }
            else
            {
                gZeroDelayCnt = 5; 
            }
              
            return;
         }  
         else
         {//正常加料，远小于阀门关闭值
           
         }
    }  
    
    
    
    if(STATE_ZERO_DELAY == gRunState )
    {
       gZeroDelayCnt--;
       if( 0 >= gZeroDelayCnt)
       {
          newRec.startTime    = gStartTime;
          newRec.stopTime     = timeNowX;
          newRec.fQuantiSche  = user_cfg_tab[QUANTIFY_CUR_VAL];
          newRec.fLastVal     = Xsram[FeedVal].fValue;
          newRec.nEndFlag     = End_Normal;

          SEGGER_RTT_printf(0, "normal end  %02d-%02d-%02d %02d:%02d:%02d\r\n", 
                   timeNow.nYear, timeNow.nMonth,  timeNow.nDay,
                   timeNow.nHour, timeNow.nMinute, timeNow.nSecond);

          lgAddQuantOpernRec(&newRec);



        

          Xsram[FeedTimes].lValue = Xsram[FeedTimes].lValue + 1; 
          Xsram[FeedDuration].lValue += (newRec.stopTime - newRec.startTime);
          Xsram[FeedSum].fValue += Xsram[FeedVal].fValue;


          if(user_cfg_tab[AUTO_FEED_CNT] != 0)
          {
              if(Xsram[FeedTimes].lValue >=  user_cfg_tab[AUTO_FEED_CNT])
              {
                  FlowInit();
                  return;
              }
           }
           else
           {
               if( newRec.stopTime%(86400) >  user_cfg_tab[AUTO_FEED_END])
               {//时间超过，未完成的定量必须完成再停止吧？
                  FlowInit();
                  return;
               }
           }

           if(sys_cfg_tab[AUTO_FEED_EN])
           {
               gRunState =  STATE_IDLE;
               KeyStartProc();
           }
           else
           {
               FlowInit();
           }
           return;
       }
   }
  
    
}



	
	

	